package com.jichaoyun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jichaoyun.common.model.FileInfo;
import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.common.utils.FileUtil;
import com.jichaoyun.dao.mapper.ClientInfoMapper;
import com.jichaoyun.dao.mapper.ClientfilesMapper;
import com.jichaoyun.model.client.ClientInfo;
import com.jichaoyun.model.client.ClientInfoFiles;
import com.jichaoyun.model.client.ClientInfoVo;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = {"客户关系管理相关接口"})
@RequestMapping("/sys/clientManage")
public class ClientManageController {

    @Value("${web.upload-path}")
    private String uploadPath;

    @Autowired
    private ClientInfoMapper clientInfoMapper;

    @ApiOperation("新增客户关系记录")
    @PostMapping("/save")
    public Result<String> save(@RequestBody ClientInfo info){
        info.setModifyTime(LocalDateTime.now());
        info.setVisableUri("/dg_files/");
        Integer rows = clientInfoMapper.insert(info);
        if(rows == 1){
            return Result.success("插入客户关系成功");
        }else{
            return Result.fail("插入客户关系记录失败");
        }
    }


//    @PostMapping("/update")
//    public Result<ClientInfo> update(@RequestBody ClientInfo info){
//        Integer rows = clientInfoMapper.updateById(info);
//        if(rows == 1){
//            ClientInfo info_new = clientInfoMapper.selectById(info.getId());
//            return Result.success(info_new);
//        }else{
//            return Result.fail("修改客户关系记录失败");
//        }
//    }

    /**
     * 删除用户访问记录
     * @param cid
     * @return
     */
    @ApiOperation("删除用客户关系记录及其文件")
    @PostMapping("/delete")
    @Transactional
//    @MustLog(title = "客户关系管理模块",content = "删除客户关系信息")
    public Result<?> delete( Integer cid){
        try {
            String username = clientInfoMapper.selectById(cid).getUsername();
            Integer rows = clientInfoMapper.deleteById(cid);
            LambdaQueryWrapper<ClientInfoFiles> wp = new LambdaQueryWrapper<>();
            wp.eq(ClientInfoFiles::getUsername,username);
            List<ClientInfoFiles> clientInfoFiles = clientfilesMapper.selectList(wp);
            for (ClientInfoFiles clientInfoFile : clientInfoFiles) {
             String path =   uploadPath + clientInfoFile.getFilename();
                FileUtil fileUtil = new FileUtil();
                fileUtil.deleteFile(path);
            }
            clientfilesMapper.delete(wp);
            return Result.success("删除记录及其文件成功！");
        }catch (Exception e){
            return Result.success("删除失败，出现异常！");
        }
    }

    /**
     * 分页查询用户访问记录，默认10条
     * @param pageNo
     * @return
     */
    @ApiOperation("分页查询接口，默认10条")
    @GetMapping("/getPage")
    public Result<PagedResult> getPage(Integer pageNo){
        IPage<ClientInfo> clientIPage = new Page<>(pageNo,10);
        QueryWrapper<ClientInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("modify_time");
        PagedResult pagedResult = new PagedResult();
        IPage<ClientInfo> infoIPage= clientInfoMapper.selectPage(clientIPage,queryWrapper);

        List<ClientInfo> clientInfos = infoIPage.getRecords();
        ArrayList<ClientInfoVo> res = new ArrayList<>();
        for (ClientInfo clientInfo : clientInfos) {
            String username = clientInfo.getUsername();
            LambdaQueryWrapper<ClientInfoFiles> wp = new LambdaQueryWrapper<>();
            wp.eq(ClientInfoFiles::getUsername,username);
            List<ClientInfoFiles> clientInfoFiles = clientfilesMapper.selectList(wp);
            ArrayList<String> files = new ArrayList<>();
            for (ClientInfoFiles clientInfoFile : clientInfoFiles) {
                files.add(clientInfoFile.getFilename());
            }
            ClientInfoVo clientInfoVo = new ClientInfoVo();
            clientInfoVo.setCid(clientInfo.getId());
            clientInfoVo.setFilenames(files);
            clientInfoVo.setPrincipal(clientInfo.getPrincipal());
            clientInfoVo.setTel(clientInfo.getTel());
            clientInfoVo.setPrincipal1(clientInfo.getPrincipal1());
            clientInfoVo.setTel1(clientInfo.getTel1());
            clientInfoVo.setPrincipal2(clientInfo.getPrincipal2());
            clientInfoVo.setTel2(clientInfo.getTel2());
            clientInfoVo.setPrincipal3(clientInfo.getPrincipal3());
            clientInfoVo.setTel3(clientInfo.getTel3());
            clientInfoVo.setUsername(clientInfo.getUsername());
            clientInfoVo.setVisableUri(clientInfo.getVisableUri());
            res.add(clientInfoVo);
        }

        pagedResult.setTotal((int) infoIPage.getTotal());
        pagedResult.setPages((int) infoIPage.getPages());
        pagedResult.setRows(res);
        return Result.success(pagedResult);
    }

    
    @Autowired
    private ClientfilesMapper clientfilesMapper;

    /**
     * 客户关系上传文件和图片
     * @param file
     * @param cid
     * @return
     */
    @ApiOperation("客户关系上传文件和图片")
    @PostMapping("/upload")
    public Result<String> upload(@RequestPart("file")MultipartFile file, Integer cid){
        FileUtil util = new FileUtil();
        FileInfo info = util.upload(file,uploadPath);
        if (info==null){
            return Result.fail("存在同名的文件，请更换文件名称试试");
        }
        if(file.getSize() > 10*1024*1024){
            util.deleteFile(info.getSavePath());
            return Result.fail("文件过大");
        }else if(!(info.getSuffix().equals(".jpg")||info.getSuffix().equals(".png")
                ||info.getSuffix().equals(".JPG")||info.getSuffix().equals(".PNG")
                ||info.getSuffix().equals(".jpeg")||info.getSuffix().equals(".JPEG")
                ||info.getSuffix().equals(".pdf"))){
            util.deleteFile(info.getSavePath());
            return Result.fail("文件类型不是jpg或者pdf");
        }else{
            ClientInfo entity = clientInfoMapper.selectById(cid);
            if(entity==null){
                util.deleteFile(info.getSavePath());
                return Result.fail("此用户的记录不存在，请更新列表");
            }
            ClientInfoFiles clientInfoFiles = new ClientInfoFiles();
            clientInfoFiles.setFilename(info.getFileName());
            clientInfoFiles.setUsername(entity.getUsername());
            int insert = clientfilesMapper.insert(clientInfoFiles);
            if(insert == 1){
                entity.setModifyTime(LocalDateTime.now());
                clientInfoMapper.updateById(entity);
                return Result.success(info.getFileName(),"文件上传成功");
            }else{
                util.deleteFile(info.getSavePath());
                return Result.fail("上传文件失败");
            }
        }
    }



}
